/*
 * config parser
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 4096 /* max line size will be 4094 */


static inline unsigned short
lookup_variable(const char** const variables, unsigned short var_size,
		const char* var_name)
{
	register unsigned short i = 0;

	while (strcmp(variables[i], var_name) && i < var_size) {
		++i;
	}
	if (i == var_size)
		return -1;
	else
		return --i;
}


void
parse_config_file(char** variables, unsigned short var_size,
		char** values, unsigned short val_size,
		const char* const filename)
{
	FILE* fp;
	char* line;
	char tmp_var[BUFSIZE - 4];
	char tmp_val[BUFSIZE - 2];
	char* p_tmp_val;
	unsigned short offset = 0, i = 0;
	unsigned short index;

	line = malloc(BUFSIZE);
	fp = fopen(filename, "r");

	while (fgets(line, BUFSIZE, fp)) { /* use binsearch here */
		while (line[offset] == ' ')
			++offset;

		if (line[offset] == '#' || ( line[offset] == '/' && ( line[offset+1] == '/' || line[offset+1] == '*' ) ) )
			continue;

		strtok(line[offset], "=\";");
		index = lookup_variable(variables, var_size, line[offset]);

		if (index == -1) {
			variables = realloc(variables, ++var_size * sizeof(void*));
			variables[var_size-1] = calloc(1, BUFSIZE);

			strcpy(variables[var_size-1], line[offset]);

			values = realloc(values, ++val_size * sizeof(void*));
			values[val_size-1] = calloc(1, BUFSIZE);

			index = var_size - 1;
		}

		p_tmp_val = strtok(NULL, "=");
		strcpy(values[index], p_tmp_val);
	}
}
